package org.ece.meteo.capteurTemp;

import java.text.DecimalFormat;
import java.util.*;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.util.tracker.ServiceTracker;

public class CapteurTemp extends Thread {

	ServiceTracker tracker;
	EventAdmin ea;
	boolean isActive;
	static final String path = "org/ece/meteo/capteurTemp/1";	// used for naming the event (for post-filtering)
	double temp;
	Random ran;
	DecimalFormat twoDForm = new DecimalFormat("#.##");			// To format temperature
	
	CapteurTemp() {
		// getting EventAdmin service
		isActive = false;
		temp = 20;
		ran = new Random(System.currentTimeMillis());
		// Open a service tracker
		tracker = new ServiceTracker(Activator.BC, EventAdmin.class.getName(), null);
		tracker.open();
		ea = (EventAdmin) tracker.getService();
		isActive = true;
	}
	
	public void run() {	
		while(isActive){	
			try {
				//System.out.println("temp1 " + temp);
				if (ea != null) {
					Dictionary props = new Hashtable();
					props.put("title", "Temperature 1");
					props.put("path" , path);
					props.put("time", String.valueOf(System.currentTimeMillis()));
					props.put("data", String.valueOf(twoDForm.format(temp)));
					
					// post asynchronous event
					Event event = new Event(path, props);
					ea.postEvent(event);		
				}
				Thread.sleep(1500);		// Sleep 1.5s
				alterTemp();			// Randomly change the sensor value
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void halt(){
		// Gonna gently stop the thread
		isActive = false;
	}
	
	private void alterTemp(){
		temp += ran.nextGaussian();		// Gaussian shape, to stay "around" the initial value.
		if(temp < -270)
			temp = 20;	// then start again, don't want to show something too ridiculous...
	}
}